//
//  MKBrowseCartoonViewController.m
//  ManKeCartoon
//
//  Created by 邹功梁 on 15/10/15.
//  Copyright © 2015年 ManKe. All rights reserved.
//

#import "MKBrowseCartoonViewController.h"
#import "DataUtils.h"
#import "AFNETWORK.h"
#import "StringWithWidth.h"
#import "Reachability.h"
@interface MKBrowseCartoonViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, copy) NSString *reachString;

@end

@implementation MKBrowseCartoonViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self reachablilty];
    self.tabBarController.tabBar.hidden = YES;
//    self.navBarView.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    //self.tabBarController.tabBar.hidden = NO;
    self.navBarView.hidden = NO;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        _chapterModelArray = [[NSMutableArray alloc] init];
        _current_imgArray = [[NSMutableArray alloc] init];

        _chapterDic = [[NSMutableDictionary alloc] init];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self getData];
    
    [self setUpBackButton];
    
//    [self setUpBrowseCartoonView];
}
#pragma mark - 粗略检测网络状态
- (void)reachablilty
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"没有网络连接");
            break;
        case ReachableViaWiFi:
            _reachString = @"WIFI";
            break;
        case ReachableViaWWAN:
            _reachString = @"GPRS";
            break;
        default:
            NSLog(@"[Error] 检测错误");
            break;
    }
}
#pragma mark - 隐藏电池栏
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
    //UIStatusBarStyleDefault = 0 黑色文字，浅色背景时使用
    //UIStatusBarStyleLightContent = 1 白色文字，深色背景时使用
}
- (BOOL)prefersStatusBarHidden
{
    return YES; // 返回NO表示要显示，返回YES将hiden
}
#pragma mark - GetData
- (void)getData
{
    //    http://mobilev3.ac.qq.com/Comic/ComicDetailV2/comic_id/10460/
    
    //    http://mobilev3.ac.qq.com/Comic/chapterPictureListV2/chapter_id/102/comic_id/529460
//    NSString *chapter_id = @"4";
//    NSString *seq_no = @"92";
//    NSString *comic_id = @"529460";
//    NSLog(@"%@, %@, %ld", _chapterModel.chapter_id, _comicModel.comic_id, _seq_no);
    [AFNETWORK getDataWithNoCacheString:[NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/chapterPictureListV2/chapter_id/%@/comic_id/%@", _chapterModel.chapter_id, _comicModel.comic_id] block:^(id block) {
        
        for (NSDictionary *dic in [[block objectForKey:@"data"] objectForKey:@"img_infos"]) {
            MKImageInfosModel *imageInfosModel = [[MKImageInfosModel alloc] initWithDictionary:dic];
            [_current_imgArray addObject:imageInfosModel];
            
        }
//#warning
        [_chapterDic setValue:_current_imgArray forKey:[NSString stringWithFormat:@"%ld", _seq_no]];
        _tempArrayCount = _current_imgArray.count;
        _tempSeq_no = _chapterModel.seq_no.integerValue;
        
        
        [self setUpBrowseCartoonView];
        [self customNavBar];
        [self customBottomState];
        [self reloadBatteryInfo];
//#warning 需要传进来一个参数 seq_no
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:_chapterModel.seq_no.integerValue - 1];
        [_browseCartoonView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }];
    
}
#pragma mark - 创建相关NavBar样式
- (void)customNavBar
{
    [self.navBarView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
    
    _seq_noLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 40, SCREEN_WIDTH - 120, 20)];
    _seq_noLabel.textAlignment = NSTextAlignmentCenter;
    [_seq_noLabel setTextColor:[UIColor whiteColor]];
    NSString *countStr = [NSString stringWithFormat:@"第%ld话 (%d/%ld)", _seq_no, 1, _tempArrayCount];
    
    [_seq_noLabel setText:countStr];
    [self.navBarView addSubview:_seq_noLabel];
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 10, SCREEN_WIDTH - 120, 30)];
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    [_nameLabel setTextColor:[UIColor whiteColor]];
    [_nameLabel setText:_comicModel.title];
    [self.navBarView addSubview:_nameLabel];
    
    _nameLabel.superview.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.5];
}
#pragma mark - 创建一个返回按钮
- (void)setUpBackButton
{
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setFrame:CGRectMake(10, 18, 30, 30)];
    [_backButton setImage:[UIImage imageNamed:@"iconfont-arrowleft.png"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarView addSubview:_backButton];
}
#pragma mark - 返回按钮点击方法
- (void)backButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 创建图片浏览器
- (void)setUpBrowseCartoonView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _browseCartoonView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    _browseCartoonView.pagingEnabled = YES;
    
    [_browseCartoonView setBackgroundColor:[UIColor blackColor]];
    _browseCartoonView.dataSource = self;
    _browseCartoonView.delegate = self;
    
    // 设置可以多选
    _browseCartoonView.allowsMultipleSelection = YES;
    
    [self.view addSubview:_browseCartoonView];
    
    [self.view insertSubview:_browseCartoonView atIndex:0];
    
    [_browseCartoonView registerClass:[MKBrowseCollectionViewCell class] forCellWithReuseIdentifier:@"reuseIdentifier"];
}
#pragma mark - CollectionView DataSourcr&Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    MKChaptersModel *chapterModel = [_chapterModelArray objectAtIndex:_chapterModelArray.count - section - 1];
    NSMutableArray *current_imgArray = [NSMutableArray arrayWithArray:[_chapterDic objectForKey:chapterModel.seq_no]];
    return current_imgArray.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _chapterModelArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MKBrowseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor blackColor];
    
    MKChaptersModel *chapterModel = [_chapterModelArray objectAtIndex:_chapterModelArray.count - indexPath.section - 1];

    NSMutableArray *current_imgArray = [NSMutableArray arrayWithArray:[_chapterDic objectForKey:chapterModel.seq_no]];
    
    if (current_imgArray.count > 0) {
        MKImageInfosModel *imageInfosModel = [current_imgArray objectAtIndex:indexPath.row];
        [cell setImageInfosModel:imageInfosModel];
    }
    // 设置滚动对应集数
    NSString *seq_noStr = [NSString stringWithFormat:@"第%ld话 (%ld/%ld)", indexPath.section + 1, indexPath.row + 1, current_imgArray.count];
    [_seq_noLabel setText:seq_noStr];
    // 设置底部栏
    NSString *bottomString = [NSString stringWithFormat:@"第%ld话 %ld/%ld %@ %@", indexPath.section + 1, indexPath.row + 1, current_imgArray.count, _reachString, [self getDate]];
    CGFloat width = [StringWithWidth WidthWithText:bottomString height:10 font:[UIFont systemFontOfSize:10.]];
    [_timeLabel setFrame:CGRectMake(SCREEN_WIDTH - 30 - width - 5, 0, width, 10)];
    [_timeLabel setText:bottomString];
    [self.delegate sendSeq_no:[NSString stringWithFormat:@"第%ld话", indexPath.section+1]];

    
    cell.scrollView.minimumZoomScale = 1;
    cell.scrollView.maximumZoomScale = 2;
    [cell.tap_Image addTarget:self action:@selector(tapClick)];
    
    return cell;
}
- (void)tapClick
{
    self.navBarView.hidden = !self.navBarView.hidden;
}
#pragma mark - CollectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.navBarView.hidden) {
        self.navBarView.hidden = NO;
    }
    else
    {
        self.navBarView.hidden = YES;
    }
}
#pragma mark - 取消选择 (这里要设置多选属性为yes)
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.navBarView.hidden = YES;
}
#pragma mark - 获取当前电池电量
- (float)getBatteryLeveal
{
    return [UIDevice currentDevice].batteryLevel;
}
#pragma mark - CustomBottomState 底部状态栏
- (void)customBottomState
{
    _batteryImage = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 30, 0, 20, 10)];
    [_batteryImage setImage:[UIImage imageNamed:@"battery@2x.png"]];
    
    _batteryLevelView = [[UIView alloc] initWithFrame:CGRectMake(1, 1, (_batteryImage.frame.size.width - 3) * (-[self getBatteryLeveal]), 8)];
    [_batteryLevelView setBackgroundColor:[UIColor whiteColor]];
    
    // 底部状态栏
    
    NSString *bottomString = [NSString stringWithFormat:@"第%ld话 %d/%ld %@ %@", _seq_no, 1, _current_imgArray.count, _reachString, [self getDate]];
    CGFloat width = [StringWithWidth WidthWithText:bottomString height:10 font:[UIFont systemFontOfSize:10.]];
    
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, width, 10)];
    [_timeLabel setTextColor:[UIColor whiteColor]];
    [_timeLabel setTextAlignment:NSTextAlignmentRight];
    [_timeLabel setFont:[UIFont systemFontOfSize:10.]];
    [_timeLabel setText:bottomString];
    
    _bottomBackView = [[UIView alloc] initWithFrame:CGRectMake(_timeLabel.frame.origin.x - 5, SCREEN_HEIGHT - 15, SCREEN_WIDTH - _timeLabel.frame.origin.x, 15)];
    
    [self.view addSubview:_bottomBackView];
    [_bottomBackView addSubview:_batteryImage];
    [_batteryImage addSubview:_batteryLevelView];
    [_bottomBackView addSubview:_timeLabel];
}
- (void)setBottomView
{
    
}
#pragma mark - 获取时间
- (NSString *)getDate
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"hh:mm";
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}
- (void)getBatteryInfo
{
    [_batteryLevelView setFrame:CGRectMake(1, 1, (_batteryImage.frame.size.width - 3) * (-[self getBatteryLeveal]), 8)];
//    NSString *bottomString = [NSString stringWithFormat:@"第%ld话 %d/%ld %@ %@", _seq_no, 1, _current_imgArray.count, _reachString, [self getDate]];
//    [_timeLabel setText:bottomString];
}
- (void)reloadBatteryInfo
{
    [NSTimer scheduledTimerWithTimeInterval:60.0f target:self selector:@selector(getBatteryInfo) userInfo:nil repeats:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _contentOffSetX = scrollView.contentOffset.x;
}
#pragma mark - CollectionView滚动方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _browseCartoonView) {
        
        self.navBarView.hidden = YES;
        
        CGFloat seq_no = (scrollView.contentOffset.x / SCREEN_WIDTH);
        
        // 判断如果滑动到第二张的时候请求数据&对应集数在字典相应的key下为nil
        if ((NSInteger)seq_no == _tempArrayCount - 3 && _tempSeq_no + 1 <= _chapterModelArray.count/*&& ![_chapterDic objectForKey:[NSString stringWithFormat:@"%ld", _tempSeq_no + 1]]*/) {
            
            MKChaptersModel *chapterModel = [_chapterModelArray objectAtIndex:_chapterModelArray.count - _tempSeq_no - 1];
            
            if (![_chapterDic objectForKey:[NSString stringWithFormat:@"%ld", _tempSeq_no + 1]]) {
                //        NSLog(@"******%@", chapterModel.chapter_id);
                [AFNETWORK getDataWithNoCacheString:[NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/chapterPictureListV2/chapter_id/%@/comic_id/%@", chapterModel.chapter_id, _comicModel.comic_id] block:^(id block) {
                    
                    NSMutableArray *array = [[NSMutableArray alloc] init];
                    
                    for (NSDictionary *dic in [[block objectForKey:@"data"] objectForKey:@"img_infos"]) {
                        MKImageInfosModel *imageInfosModel = [[MKImageInfosModel alloc] initWithDictionary:dic];
                        [array addObject:imageInfosModel];
                    }
                    
                    //                NSLog(@"################%@", chapterModel.seq_no);
                    if (![_chapterDic objectForKey:chapterModel.seq_no]) {
//                                            NSLog(@"%@", chapterModel.seq_no);
                        
                        [_chapterDic setValue:array forKey:chapterModel.seq_no];
                        
                        _tempArrayCount = _tempArrayCount + array.count;
                        
                        _tempSeq_no = chapterModel.seq_no.integerValue;
                        
                        [_browseCartoonView reloadData];
                    }
                }];
            }
        }
        if (seq_no < 0 && _seq_no != 1) {
            MKChaptersModel *chapterModel = [_chapterModelArray objectAtIndex:_chapterModelArray.count - _seq_no + 1];
            
//                    NSLog(@"******%@", chapterModel.chapter_id);
            [AFNETWORK getDataWithNoCacheString:[NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/chapterPictureListV2/chapter_id/%@/comic_id/%@", chapterModel.chapter_id, _comicModel.comic_id] block:^(id block) {
                
                NSMutableArray *array = [[NSMutableArray alloc] init];
                
                for (NSDictionary *dic in [[block objectForKey:@"data"] objectForKey:@"img_infos"]) {
                    MKImageInfosModel *imageInfosModel = [[MKImageInfosModel alloc] initWithDictionary:dic];
                    [array addObject:imageInfosModel];
                }
                if (![_chapterDic objectForKey:chapterModel.seq_no]) {
                    [_chapterDic setValue:array forKey:chapterModel.seq_no];
                    _tempArrayCount = array.count + _tempArrayCount;
                    _seq_no = chapterModel.seq_no.integerValue;
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:array.count - 1 inSection:_seq_no - 1];
                    
                    [_browseCartoonView reloadData];
                    
                    [_browseCartoonView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
                }
            }];
        }
        
        // 正滑
//        if (scrollView.contentOffset.x - _contentOffSetX == SCREEN_WIDTH) {
//            
//            MKChaptersModel *chapterModel = [_chapterModelArray objectAtIndex:_chapterModelArray.count - _seq_noCount - 1];
//            NSLog(@"##########%@", chapterModel.seq_no);
//            NSLog(@"*********%ld", (NSInteger)seq_no);
//            NSLog(@"~~~~~~~~~~%ld", _arrayCount);
//            if ((NSInteger)seq_no == _arrayCount) {
//                _tempCount = [[_chapterDic objectForKey:chapterModel.seq_no] count];
//                _arrayCount = _arrayCount + [[_chapterDic objectForKey:chapterModel.seq_no] count];
////                _tempCount = _tempCount + _arrayCount;
//                _seq_noCount = chapterModel.seq_no.integerValue;
//            }
//            
//            NSString *seq_noStr = [NSString stringWithFormat:@"第%ld话 (%ld/%ld)", _seq_noCount, _tempCount - _arrayCount + (NSInteger)seq_no + 1, _tempCount];
//            [_seq_noLabel setText:seq_noStr];
//        }
//        // 反滑
//        if (_contentOffSetX - scrollView.contentOffset.x == SCREEN_WIDTH)
//        {
//            MKChaptersModel *chapterModel = [_chapterModelArray objectAtIndex:_chapterModelArray.count - _seq_noCount + 1];
//            NSLog(@"#########%ld", (NSInteger)seq_no);
//            NSLog(@"$$$$$$$$$$%ld", _tempCount);
//            NSLog(@"!!!!!!!!!!%ld", _arrayCount);
//            NSLog(@"&&&&&&&&&%ld", _rightArrayCount);
//            if ((NSInteger)seq_no + _tempCount == _arrayCount - 1) {
//                _arrayCount = [[_chapterDic objectForKey:chapterModel.seq_no] count];
//                NSLog(@"^^^^^^%ld", [[_chapterDic objectForKey:chapterModel.seq_no] count]);
//                _tempCount = _arrayCount;
//                _seq_noCount = chapterModel.seq_no.integerValue;
//            }
//            if ((NSInteger)seq_no > _tempCount) {
//                _rightArrayCount = (NSInteger)seq_no - _tempCount;
//                NSString *seq_noStr = [NSString stringWithFormat:@"第%ld话 (%ld/%ld)", _seq_noCount, _rightArrayCount + 1, _tempCount];
//                [_seq_noLabel setText:seq_noStr];
//            }
//            else
//            {
//                
//                NSString *seq_noStr = [NSString stringWithFormat:@"第%ld话 (%ld/%ld)", _seq_noCount, (NSInteger)seq_no + 1, _tempCount];
//                [_seq_noLabel setText:seq_noStr];
//            }
//            NSLog(@"%@", chapterModel.seq_no);
//        }
        
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
